<?php

namespace app\command\task\YoPoint;

use app\library\DataCollect\YoPointBrand\TerminalStruct;
use app\model\BaseModel;
use app\model\device\DeviceBaseModel;
use app\mongo\YoPoint\YoPointBrandTerminalMongo;
use app\service\DataCollect\YoPoint\YoPointBrandService;
use think\console\Command;
use think\console\Input;
use think\console\Output;

/**
 * 同步友朋设备列表
 */
class YoPointBrandAsyncTerminals extends Command
{
    private YoPointBrandService $yoPointService;

    protected function configure()
    {
        // 指令配置
        $this->setName('同步友朋设备列表')
            ->setDescription('同步友朋设备列表');
        $this->yoPointService = new YoPointBrandService();
    }

    protected function execute(Input $input, Output $output)
    {
        $this->terminalList();
    }

    /**
     * 设备列表同步
     * @return void
     */
    private function terminalList()
    {
        $pageSize = 50;
        $firstPage = 1;
        $terminalListRes = $this->yoPointService->terminalTerminalList($firstPage, $pageSize);
        $dataList = $terminalListRes->data['data'];
        $lastPage = $terminalListRes->data['last_page'];
        $currentPage = $terminalListRes->data['current_page'];
        for ($i = $currentPage + 1; $i <= $lastPage; $i++) {
            $terminalListRes = $this->yoPointService->terminalTerminalList($i, $pageSize);
            $dataList = array_merge($dataList, $terminalListRes->data['data']);
        }

        if (!empty($dataList)) {
            $mongo = new YoPointBrandTerminalMongo();
            $model = new DeviceBaseModel();
            foreach ($dataList as $terminalStruct) {
                /**
                 * @var TerminalStruct $terminalStruct
                 */
                $modelData = [
                    'uuid' => $terminalStruct->id,
                    'name' => $terminalStruct->Name,
                    'work_place_uuid' => $terminalStruct->OID,
                    'data_source_from' => BaseModel::dataSourceFromYoPoint,
                ];

                // mongo 处理
                $isEmpty = $mongo->where(['id' => $terminalStruct->id])->findOrEmpty()->isEmpty();
                if ($isEmpty) {
                    echo "Mongo不存在数据,进行保存" . PHP_EOL;
                    $mongo->insertOne($terminalStruct->toArray());
                } else {
                    echo "Mongo存在数据, 更新数据" . PHP_EOL;
                    $mongo->updateByWehere($terminalStruct->toArray(), ['id' => $terminalStruct->id]);
                }

                // model 处理
                $isEmpty = $model->where(['uuid' => $modelData['uuid']])->findOrEmpty()->isEmpty();
                if ($isEmpty) {
                    echo "Model不存在数据,进行保存" . PHP_EOL;
                    $model->insertOne($modelData);
                } else {
                    echo "Model存在数据, 更新数据" . PHP_EOL;
                    $model->updateByWehere($modelData, ['uuid' => $modelData['uuid']]);
                }
            }
        }

    }
}